# !/usr/bin/env python
# -*- coding:utf-8 -*-
'''主界面

历史:
    2019-05-18 姚彧 创建
'''

__all__ = ['neMainWindow']


import os
from PyQt5.QtWidgets import QDesktopWidget, QMessageBox, QLineEdit, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5 import QtWidgets
from events.EventCenter import (EventDispatcher, EventContext)
from events.EventNames import EventNames
from tool.Singleton import Singleton
from stock.CN163 import CN163Tool
from ui.StockTable import StockTableWidget


def explorer_file(filename):
    '''打开文件(目录)'''
    if os.path.isfile(filename) or os.path.isdir(filename):
        os.startfile(filename)
    else:
        print('[%s]不存在!' % filename)

class neMainWindow(QtWidgets.QMainWindow, Singleton):
    def __init__(self):
        super().__init__()
        self.__init_environ()
        self.__init_ui()

    def emit(self, *args, **kwargs):
        return EventDispatcher().emit(*args, **kwargs)

    def __init_environ(self):
        context = EventContext()
        self.emit('App.Environ.GetAll', context)
        self.__enriron = context['value']

    def __init_menu(self):
        # 菜单栏
        menu_control = self.menuBar().addMenu('文件(&F)')
        action = menu_control.addAction('退出(&X)')
        action.triggered.connect(self.close)

        menu_help = self.menuBar().addMenu('帮助(&H)')
        action = menu_help.addAction('关于(&A)...')
        action.triggered.connect(self.about)
        action = menu_help.addAction('关于QT')
        action.triggered.connect(self.aboutqt)

        # 状态栏
        self.statusBar().showMessage('程序已就绪...')

    def __init_main_toolbar(self):
        toolbar = self.addToolBar('标准工具栏')
        holder = QWidget(toolbar)
        hbox = QtWidgets.QHBoxLayout()
        hbox.setContentsMargins(0, 0, 10, 0)
        holder.setLayout(hbox)
        toolbar.addWidget(holder)

        self.stockEdit = stockEdit = QLineEdit()
        stockEdit.setText('300021')
        stockEdit.returnPressed.connect(self.findStock)
        hbox.addWidget(stockEdit)

        btnFind = QPushButton('搜索(&S)')
        btnFind.clicked.connect(self.findStock)
        hbox.addWidget(btnFind)

        btnFind = QPushButton('上一只(&P)')
        btnFind.clicked.connect(self.findPrevStock)
        hbox.addWidget(btnFind)

        btnFind = QPushButton('下一只(&N)')
        btnFind.clicked.connect(self.findNextStock)
        hbox.addWidget(btnFind)

        QCheckBox = QtWidgets.QCheckBox
        self.cbAll = QCheckBox('全部', self)
        self.cbAll.stateChanged.connect(self.changeQuanterYear)
        self.cbOne = QCheckBox('1季度', self)
        self.cbOne.stateChanged.connect(self.changeQuanterYear)
        self.cbTwo = QCheckBox('2季度', self)
        self.cbTwo.stateChanged.connect(self.changeQuanterYear)
        self.cbThree = QCheckBox('3季度', self)
        self.cbThree.stateChanged.connect(self.changeQuanterYear)
        self.cbFour = QCheckBox('4季度', self)
        self.cbFour.stateChanged.connect(self.changeQuanterYear)
        for cb in (self.cbAll, self.cbOne, self.cbTwo, self.cbThree, self.cbFour):
            hbox.addWidget(cb)

        hbox.addStretch()

    def findStock(self):
        stock = self.stockEdit.text()
        try:
            stockdf = CN163Tool().read_stock(stock)
            self.stockTable.fill(stockdf)
            self.drawStockChart()
        except:
            pass

    def findPrevStock(self):
        self.findStepStock(-1)

    def findNextStock(self):
        self.findStepStock(1)

    def findStepStock(self, step):
        assert step in (-1, 1)
        stock = self.stockEdit.text()
        try:
            stock = '%06d' % (int(stock) + step)
            self.stockEdit.setText(stock)
            self.findStock()
        except:
            pass

    def about(self):
        box = QMessageBox(QMessageBox.Information, '关于{app_name}'.format(**self.__enriron), '作者: {author}\n版本: {version}\n日期: {version_date}      '.format(**self.__enriron))
        box.addButton(self.tr("确定"), QMessageBox.YesRole)
        box.setWindowIcon(self.app_icon)
        box.exec_()

    def aboutqt(self):
        QMessageBox.aboutQt(self)

    def __get_title(self):
        return self.title_prefix

    def __init_ui(self):
        self.app_icon = QIcon(':/icons/app.ico')
        self.title_prefix = '{app_name}'.format(**self.__enriron)
        self.setWindowTitle(self.__get_title())

        self.__init_menu()
        self.__init_main_toolbar()
        self.stockTable = StockTableWidget(self)
        self.stockTable.horizontalHeader().sectionClicked.connect(self.horizontalHeaderSectionClicked)
        self.setCentralWidget(self.stockTable)
        self.setWindowIcon(self.app_icon)

        self.setGeometry(0, 0, 1366, 768)
        self.__center()
        self.show()

    def horizontalHeaderSectionClicked(self, column):
        self.stockTable.stockColumns = self.stockTable.stockdf.columns[column]
        self.drawStockChart()

    def changeQuanterYear(self, state):
        indexes = [cb.isChecked() for cb in (self.cbAll, self.cbOne, self.cbTwo, self.cbThree, self.cbFour)]
        self.stockTable.updateDrawIndexes(indexes)
        self.drawStockChart()

    def drawStockChart(self):
        if hasattr(self.stockTable, 'stockdf'):
            indexes = getattr(self.stockTable, 'filterIndexes', None)
            df = self.stockTable.stockdf
            if indexes is None or (not any(indexes)) or indexes[0]:
                pass
            elif indexes:
                ops = []
                for i,v in enumerate(indexes[1:]):
                    if v:
                        ops.append('%02d$' % (i + 1))
                df = df.filter(regex = '|'.join(ops), axis = 0)
            context = EventContext(df=df)
            if hasattr(self.stockTable, 'stockColumns'):
                context['column'] = getattr(self.stockTable, 'stockColumns')
            self.emit('on_draw', context)

    def __center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)

    def on_event_add_dock(self, context:EventContext, *args, **kwargs):
        assert context.path == EventNames.UI_Dock_Add
        pane_args = context.get('pane_args')
        self.addDockWidget(*pane_args)

    @classmethod
    def register_events(cls):
        self = cls.getInstance()
        EventDispatcher().register(EventNames.UI_Dock_Add, self.on_event_add_dock)
